﻿// Decompiled with JetBrains decompiler
// Type: Microsoft.InfoCards.LifeTimeMonitor
// Assembly: infocard, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// MVID: 8E14765A-6610-409A-BA36-099A0642905D
// Assembly location: E:\git\ALLIDA\windll\infocard.exe

using Microsoft.InfoCards.Diagnostics;
using Microsoft.Win32;
using System;
using System.ServiceProcess;
using System.Timers;

namespace Microsoft.InfoCards
{
  internal class LifeTimeMonitor
  {
    private object m_syncRoot = new object();
    private const int DefaultShutdownInterval = 3600000;
    private const int MinimumShutdownInterval = 60000;
    private const string ServiceIdleTimeValue = "ServiceIdleTime";
    private int m_activeCount;
    private bool m_isShuttingDown;
    private Timer m_shutdownTimer;

    public LifeTimeMonitor()
    {
      int num = 3600000;
      using (new SystemIdentity(false))
      {
        using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(InfoCardConstants.RegistryKey, false))
        {
          if (registryKey != null)
          {
            object obj = registryKey.GetValue("ServiceIdleTime", (object) 3600000);
            if (obj is int)
            {
              if ((int) obj >= 60000)
                num = (int) obj;
            }
          }
        }
      }
      this.m_activeCount = 0;
      this.m_shutdownTimer = new Timer((double) num);
      this.m_shutdownTimer.Elapsed += new ElapsedEventHandler(this.OnShutdown);
      this.m_shutdownTimer.AutoReset = false;
      this.m_isShuttingDown = false;
      this.StartShutdownTimer();
    }

    public void AddClient()
    {
      lock (this.m_syncRoot)
      {
        InfoCardTrace.Assert(this.m_activeCount >= 0, "incorrect active count");
        if (this.m_isShuttingDown)
          throw InfoCardTrace.ThrowHelperError((Exception) new ServiceBusyException());
        ++this.m_activeCount;
        if (1 != this.m_activeCount)
          return;
        this.StopShutdownTimer();
      }
    }

    public void RemoveClient()
    {
      lock (this.m_syncRoot)
      {
        InfoCardTrace.Assert(this.m_activeCount > 0, "invalid active count");
        --this.m_activeCount;
        if (this.m_activeCount != 0)
          return;
        this.StartShutdownTimer();
      }
    }

    private void OnShutdown(object sender, ElapsedEventArgs args)
    {
      lock (this.m_syncRoot)
      {
        if (this.m_activeCount > 0)
          return;
        this.m_shutdownTimer.Enabled = false;
        this.m_isShuttingDown = true;
        InfoCardTrace.Audit(EventCode.AUDIT_SERVICE_IDLE_STOP);
      }
      using (new SystemIdentity(false))
        new ServiceController("idsvc").Stop();
    }

    private void StartShutdownTimer()
    {
      this.m_shutdownTimer.Start();
    }

    private void StopShutdownTimer()
    {
      this.m_shutdownTimer.Stop();
    }
  }
}
